/**
 * WhiMAIcpp - C++ interface for the Whiskey Media APIs.
 *  Copyright (C) 2010  Anders Bugge
 *
 *  This program is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

#include "common.h"

namespace WM
{

Array::Array( const json::Array& array )
{
	arrayElm = new json::UnknownElement( array );
}

Array::~Array()
{
	if( arrayElm )
		delete arrayElm;

	for( std::map<std::string, Array*>::iterator it = arrays.begin(); it != arrays.end(); it++ )
		delete it->second;
}

size_t Array::Size() const
{
	try
	{
		return (size_t)((json::Array&)(*arrayElm)).Size();
	}
	catch( const json::Exception& e)
	{
#ifdef WHIMAI_DEBUG
		std::cout << "JSON ERROR: " << e.what() << std::endl;
#endif
	}
	return 0;
}

double Array::asValue( unsigned int index, std::string item, bool* ok )
{
	try
	{
		const json::UnknownElement& uElm = ((json::Array&)(*arrayElm))[index][item];
		if( ok )
			*ok = true;

		return ((json::Number)uElm).Value();
	}
	catch( const json::Exception& e)
	{
#ifdef WHIMAI_DEBUG
		std::cout << "JSON ERROR: " << e.what() << std::endl;
#endif
		if( ok )
			*ok = false;
	}
	return 0.0;
}

std::string Array::asString( unsigned int index, std::string item, bool* ok )
{
	try
	{
		const json::UnknownElement& uElm = ((json::Array&)(*arrayElm))[index][item];
		if( ok )
			*ok = true;

		return ((json::String)uElm).Value();
	}
	catch( const json::Exception& e)
	{
#ifdef WHIMAI_DEBUG
		std::cout << "JSON ERROR: " << e.what() << std::endl;
#endif
		if( ok )
			*ok = false;
	}
	return "";
}

Array* Array::asArray( unsigned int index,std::string item, bool* ok )
{
	if( arrays.find(item) != arrays.end() )
		return arrays[item];

	bool okay = false;
	try
	{
		const json::UnknownElement& uElm = ((json::Array&)(*arrayElm))[index][item];
		if( ok )
			*ok = okay;

		if( okay )
		{
			arrays[item] = new Array( ((const json::Array&)uElm) );
			return arrays[item];
		}
	}
	catch( const json::Exception& e)
	{
#ifdef WHIMAI_DEBUG
		std::cout << "JSON ERROR: " << e.what() << std::endl;
#endif
	}

	return NULL;
}

} // VMA

